package com.lc.demo2.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author liuc
 * @date 2021/5/10
 * @description
 **/
public class SessionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验session
        HttpSession session = request.getSession();
        System.out.println("request url: " + request.getRequestURI() + ", session id : " + session.getId());
        //校验是否有登录信息
        Object username = session.getAttribute("username");
        System.out.println("username: " + username);
        if(username == null){
            response.sendRedirect(request.getContextPath() + "/toLogin");
            return false;
        }
        System.out.println(username);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
